package com.may.wind.service;

import com.may.wind.dao.MenuRepository;
import com.may.wind.entity.Menu;
import com.may.wind.entity.RoleMenu;
import com.may.wind.entity.User;
import com.may.wind.entity.UserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class MenuService {
    @Autowired
    MenuRepository menuRepository;

    @Autowired
    UserService userService;

    @Autowired
    UserRoleService userRoleService;

    @Autowired
    RoleMenuService roleMenuService;

    public List<Menu> getAllByParentId(long parentId) {
        return menuRepository.findAllByParentId(parentId);
    }

    public List<Menu> getMenusByCurrentUser() {
        // 获取当前用户信息
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        User user = (User) principal;
        List<Long> roleIds = userRoleService.getAllByUserId(user.getId()).stream().map(UserRole::getRolesId).collect(Collectors.toList());

        // Get menu items of these roles.
        List<Long> menuIds = roleMenuService.findAllByRoleId(roleIds).stream().map(RoleMenu::getMenuId).collect(Collectors.toList());
        List<Menu> menus = menuRepository.findAllById(menuIds).stream().distinct().collect(Collectors.toList());

        // Adjust the structure of the menu.
        handleMenus(menus);
        return menus;
    }

    public List<Menu> getMenusByRoleId(long roleId) {
        List<Long> menuIds = roleMenuService.findAllByRoleId(roleId).stream().map(RoleMenu::getMenuId).collect(Collectors.toList());
        List<Menu> menus = menuRepository.findAllById(menuIds);
        handleMenus(menus);
        return menus;
    }

    /**
     * Adjust the Structure of the menu.
     *
     * @param menus Menu items list without structure
     */
    public void handleMenus(List<Menu> menus) {
        menus.forEach(menu -> {
            List<Menu> children = getAllByParentId(menu.getId());
            menu.setChildren(children);
        });

        menus.removeIf(menu -> menu.getParentId() != 0);
    }
}
